package com.xiaoshuidi.cloud.module.rooms.controller.admin.reservation;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfWriter;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.module.contract.api.OrderFeesApi;
import com.xiaoshuidi.cloud.module.contract.vo.OrderFeesDetailApiVo;
import com.xiaoshuidi.cloud.module.contract.vo.OrderInformationVo;
import com.xiaoshuidi.cloud.module.finance.api.finance.FinanceMoneyFlowApi;
import com.xiaoshuidi.cloud.module.finance.api.finance.dto.FinanceMoneyFlowRespDTO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.reservation.vo.RoomReceiptRespVO;
import com.xiaoshuidi.cloud.module.rooms.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.rooms.service.RoomReceiptService;
import com.xiaoshuidi.cloud.module.rooms.utils.PdfUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 收据管理")
@RequestMapping(ApiConstants.NAME + "/room-receipt")
@RestController
public class RoomReceiptController {
    @Resource
    private RoomReceiptService roomReceiptService;
    @Resource
    private OrderFeesApi orderFeesApi;
    @Resource
    private FinanceMoneyFlowApi financeMoneyFlowApi;

    @GetMapping("/cancel")
    @Operation(summary = "作废收据")
    @Parameter(name = "orderId", description = "账单id", example = "1024")
    public CommonResult<Boolean> cancel(@RequestParam(value = "orderId", required = false) Long orderId) {
        roomReceiptService.cancel(orderId);
        return success(true);
    }

    @GetMapping("/down")
    @Operation(summary = "获取收据信息")
    @Parameter(name = "orderId", description = "账单id", example = "1024")
    public CommonResult<RoomReceiptRespVO> down(@RequestParam(value = "orderId", required = false) Long orderId) {
        return success(roomReceiptService.down(orderId));
    }


    /**
     * 租客账单PDF
     * @param id
     * @param sourceBizId
     * @param sourceBizType
     * @param response
     * @throws Exception
     */
    @GetMapping("/tenantBillPdf")
    public void pdf(@RequestParam("id") Long id,
                    @RequestParam(value = "sourceBizId", required = false) String sourceBizId,
                    @RequestParam(value = "sourceBizType", required = false) String sourceBizType,
                    @RequestParam(value = "billPrint", required = false,defaultValue = "1") String billPrint,
                    HttpServletResponse response) throws Exception {
        //查询流水
        CommonResult<OrderFeesDetailApiVo> result = orderFeesApi.orderDetail(id);
        //查询账单信息
        CommonResult<List<FinanceMoneyFlowRespDTO>> appList = financeMoneyFlowApi.getAppList(sourceBizId, sourceBizType);

        Font header = PdfUtils.getFont();
        header.setSize(18);
        header.setStyle(Font.FontStyle.BOLD.getValue());
        Font bold = PdfUtils.getFont();
        bold.setStyle(Font.FontStyle.BOLD.getValue());

        PdfUtils.PdfDoc doc = PdfUtils.newPdfDoc();
        OutputStream os = response.getOutputStream();

        if (!appList.isSuccess() || appList.getData() == null || !result.isSuccess() || result.getData() == null) {
            doc.addParagraph("未找到结算信息");
            doc.close();
            os.close();
            return;
        }
        List<FinanceMoneyFlowRespDTO> financeMoneyFlowRespDTOS = appList.getData();
        FinanceMoneyFlowRespDTO financeMoneyFlowDO = financeMoneyFlowRespDTOS.get(0);
        OrderFeesDetailApiVo data = result.getData();

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(String.format("租客账单_%s.pdf", DateUtil.format(new Date(), "yyyyMMddHHmmss")), "UTF-8"));
        response.setContentType("application/pdf;charset=UTF-8");

        PdfWriter.getInstance(doc.getDoc(), os);
        doc.open();

        doc.addParagraph(DateUtil.format(new Date(), "yyyy/MM/dd"));
        doc.addTable(4, tb -> {
                    // 主表单信息
                    tb.addCell("租客账单(一联)", 4, header, cell -> {
                                cell.setPaddingTop(5);
                                cell.setPaddingBottom(10);
                            })
                            .addCell("业务信息", 4, bold, Element.ALIGN_LEFT)
                            .addCell("合同账单编号").addCell(financeMoneyFlowDO.getRoomRentOrderNo(), 3)
                            .addCell("合同开始", financeMoneyFlowDO.getRoomRentOrderStart().format(DateTimeFormatter.ISO_LOCAL_DATE), "合同结束",
                                    financeMoneyFlowDO.getRoomRentOrderEnd().format(DateTimeFormatter.ISO_LOCAL_DATE))
                            .addCell("业务门店", financeMoneyFlowDO.getApartmentName(), "业务管家", financeMoneyFlowDO.getOperator())
                            .addCell("房屋位置").addCell(financeMoneyFlowDO.getRoomName(), 3)
                            .addCell("租户名称", financeMoneyFlowDO.getRentCustomer(), "支付状态", financeMoneyFlowDO.getStatusDesc())
                            .addCell("支付方式", financeMoneyFlowDO.getPayMethod(), "交易流水号", financeMoneyFlowDO.getFlowNo())
                            .addCell("附件").addCell(financeMoneyFlowDO.getRemark() , 3);
                    // 账单信息

                    tb.addCell("账单信息", 4, bold, Element.ALIGN_LEFT)
                            .addCell("费用名称", "费用金额", "已收金额", "备注");

                    for (OrderInformationVo d : data.getOrderFeesDetaillVos()) {
                        tb.addCell(d.getFeeName(), d.getAmount().toString(), d.getPaidAmount().toString(), d.getRemark());
                    }
                    tb.addCell("总计").addCell(financeMoneyFlowDO.getTradeAmount().toString() + "元", 3);
                    tb.options(t -> {
                        t.setWidthPercentage(100);
                        try {
                            t.setWidths(new float[]{18f, 32f, 18f, 32f});
                        } catch (DocumentException ignore) {
                        }
                    });
                }
        );

        //查看是否二联
        if (billPrint.equals("2")) {
            doc.addParagraph(DateUtil.format(new Date(), "yyyy/MM/dd"));
            doc.addTable(4, tb -> {
                        // 主表单信息
                        tb.addCell("租客账单(二联)", 4, header, cell -> {
                                    cell.setPaddingTop(5);
                                    cell.setPaddingBottom(10);
                                })
                                .addCell("业务信息", 4, bold, Element.ALIGN_LEFT)
                                .addCell("合同账单编号").addCell(financeMoneyFlowDO.getRoomRentOrderNo(), 3)
                                .addCell("合同开始", financeMoneyFlowDO.getRoomRentOrderStart().format(DateTimeFormatter.ISO_LOCAL_DATE), "合同结束",
                                        financeMoneyFlowDO.getRoomRentOrderEnd().format(DateTimeFormatter.ISO_LOCAL_DATE))
                                .addCell("业务门店", financeMoneyFlowDO.getApartmentName(), "业务管家", financeMoneyFlowDO.getOperator())
                                .addCell("房屋位置").addCell(financeMoneyFlowDO.getRoomName(), 3)
                                .addCell("承租人", financeMoneyFlowDO.getRenter(), "经办人", financeMoneyFlowDO.getOperator())
                                .addCell("支付方式", financeMoneyFlowDO.getPayMethod(), "交易流水号", financeMoneyFlowDO.getFlowNo())
                                .addCell("附件").addCell(financeMoneyFlowDO.getRemark() , 3);
                        // 账单信息

                        tb.addCell("账单信息", 4, bold, Element.ALIGN_LEFT)
                                .addCell("费用名称", "费用金额", "已收金额", "备注");

                        for (OrderInformationVo d : data.getOrderFeesDetaillVos()) {
                            tb.addCell(d.getFeeName(), d.getAmount().toString(), d.getPaidAmount().toString(), d.getRemark());
                        }
                        tb.addCell("总计").addCell(financeMoneyFlowDO.getTradeAmount().toString() + "元", 3);
                        tb.options(t -> {
                            t.setWidthPercentage(100);
                            try {
                                t.setWidths(new float[]{18f, 32f, 18f, 32f});
                            } catch (DocumentException ignore) {
                            }
                        });
                    }
            );
        }
        doc.getDoc().newPage();
        doc.close();
        os.close();
    }
}
